package com.fengwan.wastesort.ui.fragment

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.chad.library.adapter.base.BaseQuickAdapter
import com.fengwan.wastesort.R
import com.fengwan.wastesort.adapter.WasteSortAdapter
import com.fengwan.wastesort.adapter.WasteSortAdapter2
import com.fengwan.wastesort.model.Waste
import com.fengwan.wastesort.ui.viewModel.WasteWetViewModel
import kotlinx.android.synthetic.main.fragment_waste_sort.*

class WasteWetFragment : BaseWasteFragment(), BaseQuickAdapter.RequestLoadMoreListener, Observer<List<Waste>> {


    companion object {
        fun newInstance() = WasteWetFragment()
    }

    private val adapter by lazy { WasteSortAdapter2(activity!!) }
    private val viewModel by lazy { ViewModelProviders.of(this).get(WasteWetViewModel::class.java) }
    private var isFirst = true

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_waste_sort, container, false)
    }

    override fun initListener() {
        viewModel.wetWastes.observe(this, this)
    }

    override fun onChanged(it: List<Waste>) {
        if (it.any()) {
            if (isFirst) {
                adapter.setNewData(it)
                isFirst = false
            } else {
                adapter.addData(it)
            }
//            adapter.loadMoreComplete()
        } else {
//            adapter.loadMoreEnd(true)
        }
    }

    override fun initView(view: View) {
        recycler.layoutManager = GridLayoutManager(context, 2, RecyclerView.VERTICAL, false)
        val itemHeader = getItemHeader(R.layout.item_waste_header, recycler)
//        adapter.setHeaderView(itemHeader)
        setItemHeaderContent(
            itemHeader,
            R.color.colorWasteWet,
            "湿垃圾",
            R.mipmap.icon_household,
            "即易腐垃圾，易腐的生物质生活废弃物\n如食物废料、剩饭剩菜、过期食品、瓜皮果核、花卉植物。\n◆沥干水分\n◆有外包装的应去除外包装\n◆与其他种类垃圾分开投放"
        )
//        adapter.setOnLoadMoreListener(this, recycler)
        recycler.adapter = adapter
    }

    override fun loadData(_id: Int, type: Int) {
        viewModel.loadWetWastes(_id, 3)
    }

    override fun onLoadMoreRequested() {
//        loadData(adapter.data[adapter.data.size - 1]._id)
    }

    override fun onDestroyView() {
        viewModel.wetWastes.removeObserver(this)
        super.onDestroyView()
    }

}
